package da.metricscraft.client;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

public class ArrayList2D<K, V>{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private HashMap<K, HashMap<K, V>> list;
	public ArrayList2D(){
		list = new HashMap<K, HashMap<K, V>>();
	}
	public HashMap<K, HashMap<K, V>> getMap(){
		return list;
	}
	public ArrayList<K> getKeys(V value){
		Set<Entry<K, HashMap<K,V>>> entryset = list.entrySet();
		K first = null;
		K second = null;
		HashMap<K, V> myMap = null;
		for(HashMap<K, V> map : list.values()){

			Set<Entry<K,V>> entryset2 = map.entrySet();
			for(Entry e : entryset2){
				if (e.getValue() == value){
					first = (K) e.getKey();
					myMap = map;
					break;
				}
			}
			if (myMap != null) break;
		}
		if (myMap == null){
			return null;
		}
		else{
			for(Entry e : entryset){
				if (e.getValue() == myMap){
					second = (K) e.getKey();
				}
			}
		}
		ArrayList<K> klist = new ArrayList<K>();
		klist.add(second);
		klist.add(first);
		return klist;
	}
	public boolean put(K key1, K key2, V value){
		if (list.get(key1) != null){
			if(list.get(key1).get(key2) != null){
				return false;
			}else{
				list.get(key1).put(key2, value);
				return true;
			}
		}else{
			HashMap<K, V> newYAxis = new HashMap<K, V>();
			newYAxis.put(key2, value);
			list.put(key1, newYAxis);
			return true;
		}
	}
	public V get(K key1, K key2){
		if (list.get(key1) != null){
			V temp = list.get(key1).get(key2);
			if (temp != null){
				return temp;
			}
		}
		return null;
	}
	public Collection<V> values(){
		ArrayList<V> all = new ArrayList<V>();
		for (HashMap<K, V> m : list.values()){
			for (V val : m.values()){
				all.add(val);
			}
		}
		return all;
	} 
	public String toString(){
		String retString = "";
//		for (Entry<K, HashMap<K, V>> m : list.entrySet()){
//			for (Entry<K,V> val : m.getValue().entrySet()){
//				retString += "[" + m.getKey() + "," + val.getKey() + "] - " + val.getValue() + " | ";
//			}
//		}
		retString = values().toString();
		return retString;
	}
	
}
